import os
import psutil
import socket
import uuid
import configparser


def setup_env(config_file):
    """
        配置环境
    :param config_file: 配置文件
    :return:
    """
    cf = configparser.ConfigParser()
    cf.read(config_file)

    for p in cf.keys():
        items = cf[p].items()
        for k, v in items:
            if k in os.environ:
                os.environ[k] += ';{}'.format(k)
            else:
                os.environ[k] = v


def get_host_name():
    """
        获取机器名
    :return:
    """
    return socket.gethostname()


def get_user_name():
    """
        获取登录的用户名
    :return:
    """
    return os.getlogin()


def get_local_ip():
    """
        获取当前网卡的本地ip地址
    :return:
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # 不需要真正连接到一个远程服务器，只是为了得到本机的IP地址
        s.connect(('8.8.8.8', 80))
        IP = s.getsockname()[0]
    finally:
        s.close()
    return IP


def get_mac_address():
    """
        获取当前网卡的mac地址
    :return:
    """
    node = uuid.getnode()
    mac = uuid.UUID(int=node).hex[-12:]
    return ':'.join([mac[e:e + 2] for e in range(0, 11, 2)])


def get_Hardware_info():
    """获取硬件信息：cpu,内存"""
    cpu_per = psutil.cpu_percent(interval=1)
    memory = psutil.virtual_memory()
    memory_size = int(memory.total / 1024 / 1024 / 1024)

    return f"{cpu_per}%@cpu / {memory.percent}%@{memory_size}G"
